<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-21 10:51:48
 * @LastEditTime: 2020-06-13 13:06:50
 * @LastEditors: Please set LastEditors
 -->

<template>
    <div style="width: 100%">
        <div class="headerBtn1">
            <!-- <Button type="primary"  style="position:relative;z-index:55" @click="opeartionManyVm">批量操作虚拟机</Button> -->

            <Input
                suffix="ios-search"
                placeholder="请输入设备名称"
                search
                v-model="virtualNameOfReach"
                @on-search="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
                @on-change="
                    vmCurrentPage = 1;
                    limitingReach();
                "
                clearable
                style="width: auto; position: relative; z-index: 55"
            />
            <!-- <Input suffix="ios-search" placeholder="请输入设备类型"  v-model="virtualvmTypeOfReach"  @on-search="vmCurrentPage=1;getVmListManage()"  @on-change="vmCurrentPage=1;limitingReach()" clearable  style="width: auto;position:relative;z-index:55"/> -->
            <Select filterable
                v-model="virtualvmTypeOfReach"
                filterable
                style="width: 180px"
                clearable
                placeholder="请选择设备类型"
                @on-change="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
            >
                <Option value="SERVER">SERVER</Option>
                <Option value="CLIENT">CLIENT</Option>
                <Option value="IDS">IDS</Option>
                <Option value="WAF">WAF</Option>
                <Option value="FW">FIREWALL</Option>
            </Select>
            <Input
                suffix="ios-search"
                placeholder="请输入Mac地址"
                search
                v-model="virtualMacOfReach"
                @on-search="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
                @on-change="
                    vmCurrentPage = 1;
                    limitingReach();
                "
                clearable
                style="width: auto; position: relative; z-index: 55"
                v-show="controlSearchBtn"
            />
            <Input
                suffix="ios-search"
                placeholder="请输入镜像名称"
                search
                v-model="virtualImageNameOfReach"
                @on-search="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
                @on-change="
                    vmCurrentPage = 1;
                    limitingReach();
                "
                clearable
                style="width: auto; position: relative; z-index: 55"
                v-show="controlSearchBtn"
            />
            <!-- <Input suffix="ios-search" placeholder="Enter Mac" search v-model="virtualMacOfReach"  @on-search="vmCurrentPage=1;getVmListManage()"  @on-change="vmCurrentPage=1;limitingReach()" clearable  style="width: auto;position:relative;z-index:55"/>
        <Input suffix="ios-search" placeholder="Enter Mac" search v-model="virtualMacOfReach"  @on-search="vmCurrentPage=1;getVmListManage()"  @on-change="vmCurrentPage=1;limitingReach()" clearable  style="width: auto;position:relative;z-index:55"/>
        <Input suffix="ios-search" placeholder="Enter Mac" search v-model="virtualMacOfReach"  @on-search="vmCurrentPage=1;getVmListManage()"  @on-change="vmCurrentPage=1;limitingReach()" clearable  style="width: auto;position:relative;z-index:55"/> -->
            <!-- <Cascader :data="vmAttributeData"    change-on-select @on-change="listenKeyChange" style="display:inline-block" placeholder="请选择key/value" @on-visible-change="getVmAttributeKey" v-show="controlSearchBtn"></Cascader> -->
            <Select filterable
                v-model="virtualSystypeOfReach"
                filterable
                style="width: 180px"
                clearable
                placeholder="请选择操作系统类型"
                @on-change="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
                v-show="controlSearchBtn"
            >
                <Option value="linux">Linux</Option>
                <Option value="windows">Windows</Option>
                <Option value="mac">Mac</Option>
                <Option value="unix">Unix</Option>
            </Select>
            <Select filterable
                v-model="virtualvmTypeOfReach"
                filterable
                style="width: 180px"
                clearable
                placeholder="请选择虚拟机类型"
                @on-change="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
                v-show="controlSearchBtn"
            >
                <Option value="SERVER">SERVER</Option>
                <Option value="CLIENT">CLIENT</Option>
                <Option value="DRT">DRT</Option>
                <Option value="IDS">IDS</Option>
                <Option value="DES">DES</Option>
                <Option value="WAF">WAF</Option>
                <Option value="FW">FIREWALL</Option>
            </Select>
            <Select filterable
                v-model="virtualNetworkIdOfReach"
                filterable
                style="width: 180px"
                clearable
                placeholder="请选择子网络"
                @on-open-change="reachNetworkList"
                @on-change="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
            >
                <Option v-for="(item, index) in networkData" :key="index" :value="item.networkId">{{
                    item.networkName
                }}</Option>
            </Select>
            <Select filterable
                v-model="virtualSubnetIdOfReach"
                filterable
                style="width: 180px"
                clearable
                placeholder="请选择子网"
                @on-open-change="reachSubnetList"
                @on-change="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
                v-show="controlSearchBtn"
            >
                <Option v-for="(item, index) in subnetData" :key="index" :value="item.id">{{
                    item.name + '--' + item.cidr
                }}</Option>
            </Select>
            <Select filterable
                v-model="virtualSegmentIdOfReach"
                filterable
                style="width: 180px"
                clearable
                placeholder="请选择局域网"
                @on-open-change="reachSegmentList"
                @on-change="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
                v-show="controlSearchBtn"
            >
                <Option v-for="(item, index) in segmentsData" :key="index" :value="item.id">{{
                    item.name
                }}</Option>
            </Select>
            <Button
                type="primary"
                @click="
                    vmCurrentPage = 1;
                    getVmListManage();
                "
                style="position: relative; z-index: 55"
                >搜索</Button
            >
            <!-- <Button type="dashed"  @click="controlSearch" :icon="controlSearchImage">{{controlSearchText}}</Button> -->
            <!-- <Button type="primary" @click="taskConfigerMess = true"><Icon type="md-settings" :size="16" class="position_i"/>配置管理</Button> -->
        </div>
        <Table
            border
            ref="selection"
            :columns="vmColumnsData"
            :data="vmListDataTable"
            :stripe="true"
            :show-header="true"
            id="vmListTable"
            :height="tableHeight"
            @on-selection-change="selectTableData"
            :loading="loadingTable"
            @on-select="test"
        ></Table>
        <Page
            :total="vmTotal"
            show-sizer
            :current="vmCurrentPage"
            :page-size="vmItemPage"
            :show-total="true"
            class-name="pageStyle1"
            @on-change="switchineVmCurrentPage"
            @on-page-size-change="switchVmItemPage"
            :page-size-opts="pageItemGroup"
        />
        <!-- 虚拟机元数据 -->
        <Modal
            v-model="vmMetadata"
            title="元数据"
            ok-canel="关闭"
            ok-text="保存"
            :loading="vmMetadataLoading"
            @on-cancel="cancel"
            @on-ok="SaveMetaData"
        >
            <Tag type="dot" color="primary">虚拟机：{{ vmName }}</Tag>
            <div
                v-for="(item, key) in metadataData"
                :key="key"
                style="margin: 5px 0px; text-align: left; position: relative; width: 101%"
            >
                <Input
                    placeholder="Enter key"
                    style="width: 226px"
                    v-model="item.key"
                    clearable
                ></Input>
                <Icon type="md-remove" />
                <Input
                    placeholder="Enter value"
                    style="width: 220px"
                    v-model="item.value"
                    clearable
                ></Input>
                <Icon
                    type="md-remove-circle"
                    @click="removeMetadata(key)"
                    :size="20"
                    style="cursor: pointer"
                />
            </div>
            <div>
                <Button icon="ios-add" type="dashed" size="large" @click="handleAddMetadata"
                    >添加Metadata</Button
                >
            </div>
        </Modal>
        <!-- 批量操作虚拟机面板 -->
        <Modal v-model="vmManyPanel" width="371">
            <p slot="header" style="text-align: left">
                <span>共选择了{{ vmManyNumber }}台虚拟机</span>
            </p>
            <div>
                <div>
                    <Poptip
                        v-for="(item, index) in btnData"
                        :key="index"
                        confirm
                        title="您确定要执行此操作吗?"
                        @on-ok="okVm(item)"
                        @on-cancel="cancel"
                    >
                        <Button type="primary" ghost style="margin: 5px">{{ item }}</Button>
                    </Poptip>
                </div>
            </div>
            <div slot="footer">
                <Button type="primary" @click="vmManyPanel = false">关闭</Button>
            </div>
        </Modal>
        <!-- 端口转发列表 -->
        <Modal v-model="portListPanel" width="1200">
            <p slot="header" style="font-size: 14px; text-align: left">
                <!-- <Icon type="ios-information-circle"></Icon> -->
                <span>虚拟机：{{ vmName }}</span>
            </p>
            <div style="text-align: center">
                <div style="text-align: left; margin-bottom: 10px">
                    <Button type="primary" style="margin: 5px" @click="openPortPanel"
                        >开发端口</Button
                    >
                </div>
                <Table
                    border
                    ref="selection"
                    :columns="portTableCloums"
                    :data="portTableData"
                    :stripe="true"
                    :show-header="true"
                ></Table>
            </div>
            <div slot="footer">
                <Button type="primary" @click="portListPanel = false">关闭</Button>
            </div>
        </Modal>
        <!-- 转发端口 -->
        <Modal
            v-model="openPort"
            title="添加"
            ok-canel="关闭"
            ok-text="保存"
            width="380"
            :loading="addPortLoading"
            @on-cancel="cancel"
            @on-ok="addPort"
        >
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="类型" prop="type">
                    <RadioGroup v-model="formValidate.type" @on-change="listenTypeChange">
                        <Radio label="ssh"></Radio>
                        <Radio label="rdp"></Radio>
                        <Radio label="vnc_in">vnc</Radio>
                        <Radio label="other"></Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="other" prop="customType" v-if="disabledType">
                    <Input
                        v-model="formValidate.customType"
                        style="width: 200px"
                        placeholder="请输入其他类型"
                    ></Input>
                </FormItem>
                <FormItem label="端口" prop="port">
                    <!-- <Input  type="number" min="1"  max="65535"  ></Input> -->
                    <InputNumber
                        :min="1"
                        :value="1"
                        :max="65534"
                        v-model="formValidate.port"
                        style="width: 200px"
                    ></InputNumber>
                </FormItem>
                <FormItem label="协议" prop="protocol">
                    <RadioGroup v-model="formValidate.protocol">
                        <Radio label="tcp">TCP</Radio>
                        <Radio label="udp" :disabled="disabledprototol">UDP</Radio>
                        <Radio label="icmp" :disabled="disabledprototol">ICMP</Radio>
                        <Radio label="all" :disabled="disabledprototol">ALL</Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
            <!-- <Label>端口：</Label>
        <Input type="number"/>
        <Label>类型：</Label>
        <Select filterable>
            <Option>ssh</Option>
            <Option>rdp</Option>
            <Option>vnc_in</Option>
            <Option>vnc_out</Option>
        </Select> -->
        </Modal>
        <!-- 页面loading -->
        <Spin fix v-show="isSpinShow">
            <Icon type="load-c" size="30" class="demo-spin-icon-load"></Icon>
            <div>Loading...</div>
        </Spin>
    </div>
</template>

<script>
import axios from '@/libs/axios1';
export default {
    name: 'virtualMachineMangement',
    props: ['prjId'],
    data() {
        return {
            daat: [],
            pageItemGroup: [10, 20, 30, 40],
            isSpinShow: false,
            loadingTable: true,
            vmManyPanel: false,
            vmManyNumber: '',
            vmName: '',
            vmMetadata: false,
            vmMetadataLoading: true,
            metadataData: [
                {
                    key: '',
                    value: '',
                },
            ],
            projectName: '',
            userName: '',
            vmTotal: 0,
            vmCurrentPage: 1,
            vmItemPage: 10,
            columns: [
                {
                    title: 'Name',
                    key: 'name',
                    align: 'center',
                    width: 200,
                    fixed: 'left',
                    filters: [
                        {
                            label: 'Joe',
                            value: 1,
                        },
                        {
                            label: 'John',
                            value: 2,
                        },
                    ],
                    filterMultiple: false,
                    filterMethod(value, row) {
                        if (value === 1) {
                            return row.name === 'Joe';
                        } else if (value === 2) {
                            return row.name === 'John Brown';
                        }
                    },
                },
                {
                    title: 'Other',
                    align: 'center',
                    children: [
                        {
                            title: 'Age',
                            key: 'age',
                            align: 'center',
                            width: 200,
                            sortable: true,
                        },
                        {
                            title: 'Address',
                            align: 'center',
                            children: [
                                {
                                    title: 'Street',
                                    key: 'street',
                                    align: 'center',
                                    width: 200,
                                },
                                {
                                    title: 'Block',
                                    align: 'center',
                                    children: [
                                        {
                                            title: 'Building',
                                            key: 'building',
                                            align: 'center',
                                            width: 200,
                                            sortable: true,
                                        },
                                        {
                                            title: 'Door No.',
                                            key: 'door',
                                            align: 'center',
                                            width: 200,
                                        },
                                    ],
                                },
                            ],
                        },
                    ],
                },
                {
                    title: 'Company',
                    align: 'center',
                    children: [
                        {
                            title: 'Company Address',
                            key: 'caddress',
                            align: 'center',
                            width: 200,
                        },
                        {
                            title: 'Company Name',
                            key: 'cname',
                            align: 'center',
                            width: 200,
                        },
                    ],
                },
                {
                    title: 'Company',
                    align: 'center',
                    children: [
                        {
                            title: 'Company Address',
                            key: 'caddress',
                            align: 'center',
                            width: 200,
                        },
                        {
                            title: 'Company Name',
                            key: 'cname',
                            align: 'center',
                            width: 200,
                        },
                    ],
                },
                {
                    title: 'Company',
                    align: 'center',
                    children: [
                        {
                            title: 'Company Address',
                            key: 'caddress',
                            align: 'center',
                            width: 200,
                        },
                        {
                            title: 'Company Name',
                            key: 'cname',
                            align: 'center',
                            width: 200,
                        },
                    ],
                },
                {
                    title: 'Company',
                    align: 'center',
                    children: [
                        {
                            title: 'Company Address',
                            key: 'caddress',
                            align: 'center',
                            width: 200,
                        },
                        {
                            title: 'Company Name',
                            key: 'cname',
                            align: 'center',
                            width: 200,
                        },
                    ],
                },
                {
                    title: 'Company',
                    align: 'center',
                    children: [
                        {
                            title: 'Company Address',
                            key: 'caddress',
                            align: 'center',
                            width: 200,
                        },
                        {
                            title: 'Company Name',
                            key: 'cname',
                            align: 'center',
                            width: 200,
                        },
                    ],
                },
                {
                    title: 'Gender',
                    key: 'gender',
                    align: 'center',
                    width: 200,
                    fixed: 'right',
                },
            ],
            vmColumnsData: [
                {
                    type: 'index',
                    width: 60,
                    align: 'center',
                    fixed: 'left',
                },
                {
                    title: '名称',
                    key: 'name',
                    align: 'center',
                    sortable: true,
                    minWidth: 120,
                    fixed: 'left',
                    // render:(h,params)=>{
                    //     console.log(params)
                    // }
                },
                {
                    title: '子网络名称',
                    key: 'networkName',
                    align: 'center',
                    // sortable: true,
                    minWidth: 120,
                    fixed: 'left',
                    // render:(h,params)=>{
                    //     console.log(params)
                    // }
                },
                {
                    title: '实物设备名称',
                    key: 'physicalName',
                    align: 'center',
                    minWidth: 120,
                },
                {
                    title: '网络详细信息',
                    key: '',
                    align: 'center',
                    // render:(h,params)=>{

                    // },
                    // minWidth:700,
                    children: [
                        {
                            title: '名称',
                            key: '',
                            align: 'center',
                            minWidth: 200,
                            render: (h, params) => {
                                // let k = 0;
                                // if(k>10){
                                //     return;
                                // }
                                let _this = this;
                                params = params.row;
                                let addresses = [];
                                if (params.addresses) {
                                    if (params.addresses.length != 0) {
                                        addresses = params.addresses.map((item) => {
                                            return h('div', {}, item.name);
                                        });
                                        return h('div', {}, addresses);
                                    }
                                }
                            },
                        },
                        {
                            title: 'CIDR',
                            key: '',
                            align: 'center',
                            minWidth: 200,
                            render: (h, params) => {
                                let _this = this;
                                // let k = 0;
                                // _this.refreshIndex++;
                                // if(_this.refreshIndex>_this.vmListDataTable.length){
                                //     return;
                                // }
                                // if(this.refreshIndex>10){
                                //     return
                                // }
                                // console.log('---')
                                params = params.row;
                                let addresses = [];
                                if (params.addresses && params.addresses.length != 0) {
                                    if (params.addresses.length != 0) {
                                        params.addresses.map((item) => {
                                            if (item.ips && item.ips.length != 0) {
                                                for (let i = 0; i < item.ips.length; i++) {
                                                    addresses.push(h('div', {}, item.ips[i].cidr));
                                                }
                                            }
                                        });
                                    }
                                }
                                // console.log(addresses)
                                return h('div', {}, addresses);
                            },
                        },
                        {
                            title: 'IP',
                            key: '',
                            align: 'center',
                            sortable: true,
                            minWidth: 200,
                            render: (h, params) => {
                                // let k = 0;
                                // if(k>10){
                                //     return;
                                // }
                                let _this = this;
                                params = params.row;
                                let addresses = [];
                                if (params.addresses) {
                                    if (params.addresses.length != 0) {
                                        params.addresses.map((item) => {
                                            if (item.ips && item.ips.length != 0) {
                                                for (let i = 0; i < item.ips.length; i++) {
                                                    addresses.push(
                                                        h('div', {}, item.ips[i].ipAddress)
                                                    );
                                                }
                                            }
                                        });
                                    }
                                }
                                return h('div', {}, addresses);
                            },
                        },
                        {
                            title: 'Mac地址',
                            key: 'mac',
                            align: 'center',
                            minWidth: 200,
                            render: (h, params) => {
                                // let k = 0;
                                // if(k>10){
                                //     return;
                                // }
                                let _this = this;
                                params = params.row;
                                let addresses = [];
                                if (params.addresses) {
                                    if (params.addresses.length != 0) {
                                        addresses = params.addresses.map((item) => {
                                            return h('div', {}, item.macAddress);
                                        });
                                        return h('div', {}, addresses);
                                    }
                                }
                            },
                        },
                    ],
                },
                {
                    title: '端口详细信息',
                    key: '',
                    align: 'center',
                    minWidth: 600,
                    children: [
                        // {
                        //     title: '端口',
                        //     key: 'port',
                        //     align: 'center',
                        //     minWidth:150,
                        //     render:(h,params)=>{
                        //         let _this = this;
                        //         params = params.row;
                        //         let userNameGroup = [];
                        //         if(params.devicePorts&&params.devicePorts.length!=0){
                        //             for (let index = 0; index < params.devicePorts.length; index++) {
                        //                 const element = params.devicePorts[index];
                        //                 userNameGroup.push(h('div',{},element.name))
                        //             }

                        //         }
                        //         return h('div',{},userNameGroup)
                        //     }
                        // },
                        {
                            title: '交换机名称',
                            key: '',
                            align: 'center',
                            minWidth: 150,
                            render: (h, params) => {
                                let _this = this;
                                params = params.row;
                                let userNameGroup = [];
                                if (params.devicePorts && params.devicePorts.length != 0) {
                                    for (
                                        let index = 0;
                                        index < params.devicePorts.length;
                                        index++
                                    ) {
                                        const element = params.devicePorts[index];
                                        userNameGroup.push(h('div', {}, element.switchName));
                                    }
                                }
                                return h('div', {}, userNameGroup);
                            },
                        },
                        // {
                        //     title: '交换机密码',
                        //     key: '',
                        //     align: 'center',
                        //     minWidth:150,
                        //     render:(h,params)=>{
                        //         let _this = this;
                        //         params = params.row;
                        //         let userNameGroup = [];
                        //         if(params.devicePorts&&params.devicePorts.length!=0){
                        //             for (let index = 0; index < params.devicePorts.length; index++) {
                        //                 const element = params.devicePorts[index];
                        //                 userNameGroup.push(h('div',{},element.switchPwd))
                        //             }

                        //         }
                        //         return h('div',{},userNameGroup)
                        //     }
                        // },
                        {
                            title: '交换机端口',
                            key: 'plugInType',
                            align: 'center',
                            minWidth: 150,
                            render: (h, params) => {
                                let _this = this;
                                params = params.row;
                                let userNameGroup = [];
                                if (params.devicePorts && params.devicePorts.length != 0) {
                                    for (
                                        let index = 0;
                                        index < params.devicePorts.length;
                                        index++
                                    ) {
                                        const element = params.devicePorts[index];
                                        userNameGroup.push(h('div', {}, element.switchPortName));
                                    }
                                }
                                return h('div', {}, userNameGroup);
                            },
                        },
                        // {
                        //     title: '交换机用户名',
                        //     key: 'plugInType',
                        //     align: 'center',
                        //     minWidth:150,
                        //     render:(h,params)=>{
                        //         let _this = this;
                        //         params = params.row;
                        //         let userNameGroup = [];
                        //         if(params.devicePorts&&params.devicePorts.length!=0){
                        //             for (let index = 0; index < params.devicePorts.length; index++) {
                        //                 const element = params.devicePorts[index];
                        //                 userNameGroup.push(h('div',{},element.switchUser))
                        //             }

                        //         }
                        //         return h('div',{},userNameGroup)
                        //     }
                        // },
                        // {
                        //     title: '交换机控制IP',
                        //     key: '',
                        //     align: 'center',
                        //     minWidth:150,
                        //     render:(h,params)=>{
                        //         let _this = this;
                        //         params = params.row;
                        //         let userNameGroup = [];
                        //         if(params.devicePorts&&params.devicePorts.length!=0){
                        //             for (let index = 0; index < params.devicePorts.length; index++) {
                        //                 const element = params.devicePorts[index];
                        //                 userNameGroup.push(h('div',{},element.switchIp))
                        //             }

                        //         }
                        //         return h('div',{},userNameGroup)
                        //     }
                        // },
                    ],
                },
                {
                    title: '接入信息',
                    key: 'AccessInformation',
                    align: 'center',
                    minWidth: 600,
                    children: [
                        {
                            title: '用户名',
                            key: 'ausernamege',
                            align: 'center',
                            minWidth: 150,
                            render: (h, params) => {
                                // let k = 0;
                                // if(k>10){
                                //     return;
                                // }
                                let _this = this;
                                params = params.row;
                                let userNameGroup = [];
                                // params.accesses.push('gggg')
                                if (params.accesses) {
                                    if (params.accesses.length != 0) {
                                        userNameGroup = params.accesses.map((item) => {
                                            return h('div', {}, item.username);
                                        });
                                    }
                                }
                                return h('div', {}, userNameGroup);
                            },
                        },
                        {
                            title: '密码',
                            key: 'password',
                            align: 'center',
                            minWidth: 150,
                            render: (h, params) => {
                                // let k = 0;
                                // if(k>10){
                                //     return;
                                // }
                                let _this = this;
                                params = params.row;
                                let userNameGroup = [];
                                if (params.accesses) {
                                    if (params.accesses.length != 0) {
                                        userNameGroup = params.accesses.map((item) => {
                                            return h('div', {}, item.password);
                                        });
                                    }
                                }
                                return h('div', {}, userNameGroup);
                            },
                        },
                        {
                            title: '接入类型',
                            key: 'accessType',
                            align: 'center',
                            minWidth: 150,
                            render: (h, params) => {
                                // let k = 0;
                                // if(k>10){
                                //     return;
                                // }
                                let _this = this;
                                params = params.row;
                                let userNameGroup = [];
                                if (params.accesses) {
                                    if (params.accesses.length != 0) {
                                        userNameGroup = params.accesses.map((item) => {
                                            return h('div', {}, item.accessType);
                                        });
                                    }
                                }
                                return h('div', {}, userNameGroup);
                            },
                        },
                        // {
                        //     title: '插件类型',
                        //     key: 'plugInType',
                        //     align: 'center',
                        //     minWidth:150,
                        //     render:(h,params)=>{
                        //         // let k = 0;
                        //         // if(k>10){
                        //         //     return;
                        //         // }
                        //         // console.log('plugInType')
                        //         let _this = this;
                        //         params = params.row;
                        //         let userNameGroup = [];
                        //         if(params.accesses){
                        //             if(params.accesses.length!=0){
                        //                 userNameGroup = params.accesses.map((item)=>{
                        //                     return h('div',{},item.plugInType)
                        //                 })
                        //             }
                        //         }
                        //         return h('div',{},userNameGroup)
                        //     }
                        // },
                    ],
                },
                {
                    title: '系统类型',
                    key: 'sysType',
                    minWidth: 150,
                    align: 'center',
                },
                {
                    title: '资源信息',
                    key: '',
                    align: 'center',
                    // minWidth:700,
                    children: [
                        {
                            title: 'CPU',
                            key: 'cpu',
                            sortable: true,
                            align: 'center',
                            minWidth: 120,
                        },
                        {
                            title: 'DISK(/GB)',
                            key: 'disk',
                            sortable: true,
                            align: 'center',
                            minWidth: 120,
                        },
                        {
                            title: 'RAM(/MB)',
                            key: 'ram',
                            sortable: true,
                            align: 'center',
                            minWidth: 120,
                        },
                    ],
                },
                {
                    title: '创建时间',
                    key: 'created',
                    align: 'center',
                    minWidth: 150,
                },
                {
                    title: '创建者',
                    key: 'creatorName',
                    align: 'center',
                    minWidth: 150,
                    fixed: 'right',
                },
                {
                    title: '接入',
                    key: '2',
                    align: 'center',
                    width: 180,
                    fixed: 'right',
                    render: (h, params) => {
                        let _this = this;
                        params = params.row;
                        let accessGroup = [];
                        if (params.accesses) {
                            if (params.accesses.length != 0) {
                                accessGroup = params.accesses.map((item) => {
                                    // console.log(item)
                                    return item.accessType;
                                });
                            } else {
                                // accessGroup.push("暂不支持")
                                return h('div', {}, '暂不支持');
                            }
                        }

                        accessGroup = [...new Set(accessGroup)];
                        accessGroup = Array.from(new Set(accessGroup));
                        // accessGroup.push("vnc_out");
                        let SelectGroup = [];
                        if (accessGroup.length != 0) {
                            SelectGroup = accessGroup.map((element, index) => {
                                // console.log(index)
                                if (index == 0) {
                                    return;
                                }
                                return h(
                                    'Option',
                                    {
                                        props: {
                                            value: element,
                                        },
                                    },
                                    element
                                );
                            });
                        }

                        // console.log(SelectGroup)
                        // console.log(accessGroup)
                        SelectGroup.unshift(
                            h(
                                'Option',
                                {
                                    props: {
                                        value: '0',
                                    },
                                    class: ['emptyAccess'],
                                    style: {
                                        display: 'none',
                                    },
                                },
                                ''
                            )
                        );
                        return h(
                            'div',
                            {
                                class: ['accessType'],
                            },
                            [
                                h(
                                    'Icon',
                                    {
                                        props: {
                                            type: 'md-refresh',
                                        },
                                        attrs: {
                                            title: '刷新接入连接',
                                        },
                                        on: {
                                            click(event) {
                                                event = window.event || event;
                                                // console.log('---')
                                                _this.loadingTable = true;
                                                _this.deleteAccessAisle(params.id);
                                            },
                                        },
                                        style: {
                                            fontSize: '20px',
                                            marginRight: '10px',
                                            cursor: 'pointer',
                                        },
                                    },
                                    ''
                                ),
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            label: '000',
                                            // loading:true
                                        },
                                        // label:'222',
                                        on: {
                                            click(event) {
                                                //  event = window.event || event;
                                                // var oEvent = event || window.event;
                                                // var theEvent = window.event || e;
                                                // var srcElement = theEvent.srcElement;
                                                // if (!srcElement) {
                                                //     srcElement = theEvent.target;
                                                // }
                                                // var oEvent = window.event || arguments.callee.caller.arguments[0];
                                                _this.loadingTable = true;
                                                let accessVmType =
                                                    event.srcElement.children.length > 0
                                                        ? event.srcElement.children[0].innerText
                                                        : event.srcElement.innerText;
                                                _this.vmAccess(params.id, accessVmType);
                                                // console.log(event.toElement.innerText)
                                                // console.log(this.label)
                                                // console.log(event);
                                            },
                                        },
                                        style: {
                                            borderRadius: '4px 0px 0px 4px',
                                        },
                                    },
                                    accessGroup[0]
                                ),
                                h(
                                    'Select',
                                    {
                                        props: {
                                            placeholder: '',
                                            transfer: true,
                                        },
                                        style: {
                                            width: '20px',
                                        },
                                        on: {
                                            'on-change': (value) => {
                                                $('.emptyAccess').click();
                                                if (value != 0) {
                                                    _this.vmAccess(params.id, value);
                                                }
                                                $('.accessType .ivu-select-placeholder').text('');
                                            },
                                        },
                                    },
                                    SelectGroup
                                ),
                            ]
                        );
                    },
                },
            ],
            vmListDataTable: [],
            tableHeight: '',
            virtualNameOfReach: null,
            virtualIPOfReach: '',
            virtualSystypeOfReach: '',
            virtualKeyOfReach: '',
            virtualValueOfReach: '',
            virtualvmTypeOfReach: null,
            virtualMacOfReach: '',
            virtualImageNameOfReach: '',
            virtualNetworkIdOfReach: null,
            virtualSegmentIdOfReach: '',
            virtualSubnetIdOfReach: '',
            vmKeys: [],
            vmValues: [],
            vmIdGroupStatus: [],
            vmGroupStatus: [],
            vmPassword: '',
            vmId_: '',
            updatePasswordLoading: true,
            tableListHeight: '',
            selectValue: '',
            vmAttributeData: [],
            selectTableDataGroup: [],
            btnData: [],
            setTimeClear: '',

            portListPanel: false,
            portTableCloums: [
                {
                    title: 'forwardIP',
                    key: 'forwardIp',
                    align: 'center',
                },
                {
                    title: 'forwardPort',
                    key: 'forwardPort',
                    align: 'center',
                },
                // {
                //     title:'vmName',
                //     key:'name',
                //     align:'center'
                // },
                {
                    title: 'vmIP',
                    key: 'vmIp',
                    align: 'center',
                },
                {
                    title: 'vmPort',
                    key: 'vmPort',
                    align: 'center',
                },

                {
                    title: 'type',
                    key: 'type',
                    align: 'center',
                },
                {
                    title: 'protocal',
                    key: 'protocal',
                    align: 'center',
                },
                {
                    title: 'lastExpireTime',
                    key: 'lastExpireTime',
                    align: 'center',
                },
                {
                    title: 'createName',
                    key: 'userName',
                    align: 'center',
                },
                {
                    title: 'actions',
                    key: 'actions',
                    // align:'center',
                    render: (h, params) => {
                        let _this = this;
                        params = params.row;
                        return h(
                            'Poptip',
                            {
                                style: {},
                                props: {
                                    confirm: true,
                                    title: '您确定要删除吗？',
                                },
                                on: {
                                    'on-ok': () => {
                                        _this.deleteVmPort(params.token);
                                    },
                                    'on-cancel': () => {},
                                },
                            },
                            [
                                h(
                                    'Button',
                                    {
                                        style: {
                                            margin: '5px',
                                        },
                                        props: {
                                            type: 'error',
                                        },
                                    },
                                    '删除'
                                ),
                            ]
                        );
                    },
                },
            ],
            portTableData: [],
            openPort: false,
            addPortLoading: true,
            formValidate: {
                type: 'ssh',
                port: 22,
                protocol: 'tcp',
                customType: 'customType',
            },
            ruleValidate: {
                type: [{ required: true, message: '请选择类型', trigger: 'change' }],
                port: [{ required: true, message: '请填写端口', trigger: 'blur', type: 'number' }],
                protocol: [{ required: true, message: '请选择协议', trigger: 'change' }],
                customType: [{ required: true, message: '请输入自定义类型', trigger: 'blur' }],
            },
            disabledType: false,
            disabledprototol: true,
            accessTokenRef: '',
            setTimeoutReach: '',
            networkData: [],
            subnetData: [],
            segmentsData: [],
            refreshIndex: 0,
            controlSearchBtn: false,
            controlSearchText: '更多',
            controlSearchImage: 'ios-more',
        };
    },
    created() {
        const data = [];
        for (let i = 0; i < 20; i++) {
            data.push({
                key: i,
                name: 'John Brown',
                age: i + 1,
                street: 'Lake Park',
                building: 'C',
                door: 2035,
                caddress: 'Lake Street 42',
                cname: 'SoftLake Co',
                gender: 'M',
            });
        }
        this.data = data;
        // this.prjId = this.$route.query.prjId
        this.vmCurrentPage = sessionStorage.getItem('vmCurrentPage')
            ? Number(sessionStorage.getItem('vmCurrentPage'))
            : 1;
        this.vmItemPage = sessionStorage.getItem('vmItemPage')
            ? Number(sessionStorage.getItem('vmItemPage'))
            : 10;
        // this.tableHeight = $(window).height() - 262 ;
        // console.log(this.$refs)
        // this.prjId = null;
        this.getVmListManage();
        // this.getVmAttributeKey();
        // this.getProjectInformation()
        // console.log(this.getRandomPassword(6))
    },
    methods: {
        clearSearchCriteria() {
            this.vmCurrentPage = 1;
            this.vmItemPage = 10;
            this.virtualNameOfReach = '';
            this.virtualvmTypeOfReach = '';
            this.virtualMacOfReach = '';
            this.virtualImageNameOfReach = '';
            this.virtualSystypeOfReach = '';
            this.virtualvmTypeOfReach = '';
            this.virtualNetworkIdOfReach = '';
            this.virtualSubnetIdOfReach = '';
            this.virtualSegmentIdOfReach = '';
        },
        controlSearch() {
            if (this.controlSearchBtn) {
                this.controlSearchText = '更多';
                this.controlSearchImage = 'ios-more';
            } else {
                this.controlSearchText = '收起';
                this.controlSearchImage = 'ios-arrow-up';
            }
            this.controlSearchBtn = !this.controlSearchBtn;
        },
        openPortPanel() {
            this.$refs['formValidate'].resetFields();
            this.openPort = true;
            this.formValidate.type = 'ssh';
            this.formValidate.port = 22;
            this.formValidate.protocol = 'tcp';
            this.disabledType = false;
        },
        addPort() {
            let _this = this;
            this.$refs['formValidate'].validate((valid) => {
                if (valid) {
                    _this.formValidate.type =
                        _this.formValidate.type == 'other'
                            ? _this.formValidate.customType
                            : _this.formValidate.type;
                    axios({
                        url: 'netns/access/' + _this.vmId_ + '/' + _this.formValidate.type,
                        method: 'post',
                        data: {
                            port: _this.formValidate.port,
                            protocal: _this.formValidate.protocol,
                            enablePortForward: true,
                        },
                    }).then((response) => {
                        if (response.code == 1) {
                            _this.reachVmPortsList(_this.vmId_);
                            _this.openPort = false;
                            _this.addPortLoading = false;
                            _this.$nextTick(() => {
                                _this.addPortLoading = true;
                            });
                        } else {
                            _this.$Message.error(response.message);
                            _this.addPortLoading = false;
                            _this.$nextTick(() => {
                                _this.addPortLoading = true;
                            });
                        }
                    });
                } else {
                    _this.addPortLoading = false;
                    _this.$nextTick(() => {
                        _this.addPortLoading = true;
                    });
                }
            });
        },
        getProjectInformation() {
            let _this = this;
            axios({
                url: 'topo-edit/project/' + _this.prjId,
            }).then(function (response) {
                if (response.code == 1) {
                    _this.projectName = response.attribute.project.projectname;
                } else {
                    _this.$Message.error(response.message);
                }
            });
        },
        cancel() {},
        SaveMetaData() {
            this.updateVmMetadata(this.vmId_);
        },
        removeMetadata(index) {
            this.metadataData.splice(index, 1);
            console.log(index);
            // alert(index)
        },
        handleAddMetadata() {
            this.metadataData.push({
                key: '',
                value: '',
            });
        },
        switchineVmCurrentPage(currentPage) {
            // console.log(currentPage)
            sessionStorage.setItem('vmCurrentPage', currentPage);
            this.vmCurrentPage = currentPage;
            this.getVmListManage();
            this.selectTableDataGroup = [];
        },
        switchVmItemPage(itemPage) {
            sessionStorage.setItem('vmItemPage', itemPage);
            this.vmItemPage = itemPage;
            this.getVmListManage();
            this.selectTableDataGroup = [];
        },
        getVmListManage() {
            this.refreshIndex = 0;
            let _this = this;
            _this.loadingTable = true;
            axios({
                url: 'topo-edit/deployed/physicals',
                method: 'get',
                params: {
                    pageIndex: _this.vmCurrentPage,
                    pageSize: _this.vmItemPage,
                    sortBy: 'name',
                    order: 'asc',
                    name: _this.virtualNameOfReach,
                    type: _this.virtualvmTypeOfReach,
                    networkId: _this.virtualNetworkIdOfReach,
                    projectId: _this.prjId,
                },
            }).then(function (response) {
                if (response.code == 1) {
                    sessionStorage.setItem('vmCurrentPage', _this.vmCurrentPage);
                    _this.vmIdGroupStatus = [];
                    _this.vmTotal = response.data.total;
                    _this.vmListDataTable = response.data.items;
                    // _this.vmListDataTable =  response.data.list.map(item=>{
                    //     item['_loading'] = false;
                    //     return item;
                    // });
                    // // console.log(_this.vmListDataTable)
                    _this.vmIdGroupStatus = response.data.items.map((item) => {
                        return item.id;
                    });
                    // _this.loadingTable = false
                    if (_this.vmIdGroupStatus.length != 0) {
                        //_this.reachManyVmStatus(_this.vmIdGroupStatus);
                    }
                    _this.loadingTable = false;
                } else {
                    if (response.code != -2) {
                        _this.$Message.error(response.message);
                    }
                    _this.loadingTable = false;
                }
            });
        },
        vmAccess(vmId, accessType) {
            let _this = this;
            axios({
                url: 'netns/access/' + vmId + '/' + accessType,
                method: 'POST',
                data: {},
            }).then(function (response) {
                if (response.code == 1) {
                    // var urls = data.attribute.url;
                    _this.accessTokenRef = response.attribute.token;
                    window.openTrain(
                        response.attribute.url + '&Authorization=' + localStorage.getItem('token')
                    );
                    _this.loadingTable = false;
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                    _this.loadingTable = false;
                }
            });
        },
        //操作网络
        operationVm(vmId, action, batch) {
            let _this = this;
            return axios({
                url: 'topo-control/servers/' + vmId + '/action/' + action,
                method: 'POST',
            }).then(function (response) {
                if (response.code == 1) {
                    if (batch) {
                        // _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                    } else {
                        _this.reachManyVmStatusSend(_this.vmIdGroupStatus);
                    }
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        //重置
        rebuildVm(vmId, batch) {
            let _this = this;
            return axios({
                url: 'topo-control/servers/' + vmId + '/action/rebuild',
                method: 'POST',
            }).then(function (response) {
                if (response.code == 1) {
                    if (batch) {
                        //    _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                    } else {
                        _this.reachManyVmStatusSend(_this.vmIdGroupStatus);
                    }
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        //重启
        rebootVm(vmId, batch) {
            let _this = this;
            return axios({
                url: 'topo-control/servers/' + vmId + '/action/soft_restart?type=HARD',
                method: 'POST',
            }).then(function (response) {
                if (response.code == 1) {
                    if (batch) {
                        // _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                    } else {
                        _this.reachManyVmStatusSend(_this.vmIdGroupStatus);
                    }
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        vmSwitchTypeOperation(vmId, text, params = '', batch = '') {
            let _this = this;
            switch (text) {
                case '关机':
                    _this.operationVm(vmId, 'stop', batch);
                    break;
                case '开机':
                    _this.operationVm(vmId, 'start', batch);
                    break;
                case '重置状态':
                    _this.operationVm(vmId, 'reset-state-active', batch);
                    break;
                case '重启':
                    _this.rebootVm(vmId, batch);
                    break;
                case '重置':
                    _this.rebuildVm(vmId, batch);
                    break;
                case '挂起':
                    _this.operationVm(vmId, 'suspend', batch);
                    break;
                case '暂停':
                    _this.operationVm(vmId, 'pause', batch);
                    break;
                case '恢复':
                    _this.operationVm(vmId, 'resume', batch);
                    break;
                case '取消暂停':
                    _this.operationVm(vmId, 'unpause', batch);
                    break;
                case '密码':
                    _this.vmId_ = params.id;
                    _this.vmPassword = '';
                    _this.$Modal.confirm({
                        title: '请填写密码',
                        okText: '保存',
                        // loading:true,
                        // buttonLoading:true,
                        onOk: () => {
                            //    console.log()；
                            // if(!_this.vmPassword){
                            //     _this.$Message.info("请填写密码");

                            // }
                            // _this.updatePassword(_this.vmId_,this.buttonLoading)
                            // let _this = this;
                            let that = this;
                            if (!_this.vmPassword) {
                                _this.$Message.info('请填写密码');
                                this.buttonLoading = false;
                                this.loading = false;
                                setTimeout(() => {
                                    that.buttonLoading = false;
                                }, 500);
                                return;
                            }
                            axios({
                                url:
                                    'remote/changePassword/' +
                                    vmId +
                                    '?password=' +
                                    _this.vmPassword,
                            }).then(function (response) {
                                if (response.code == 1) {
                                    _this.$Message.success('修改成功');
                                    _this.getVmListManage();
                                    // _this.$Modal.remove()
                                    // _this.updatePasswordLoading = false;
                                    // _this.$nextTick(()=>{
                                    //     _this.updatePasswordLoading = true;
                                    // })
                                } else {
                                    _this.$Message.error({
                                        content: response.message,
                                        closable: true,
                                        duration: 10,
                                    });
                                    // _this.updatePasswordLoading = false;
                                    // _this.$nextTick(()=>{
                                    //     _this.updatePasswordLoading = true;
                                    // })
                                }
                            });
                            // let code = document.getElementsByClassName('kkk')[0].children[0].children[1];
                            // code.select();
                            // document.execCommand("Copy");
                            // _this.$Message.success("复制成功")
                        },
                        render: (h) => {
                            return h(
                                'div',
                                {
                                    class: ['kkk'],
                                    id: 'ccc',
                                },
                                [
                                    h('Input', {
                                        props: {
                                            value: this.value,
                                            // 'v-model':_this.vmPassword
                                        },
                                        on: {
                                            'on-change': (event) => {
                                                console.log(event);
                                                _this.vmPassword = event.target.value;
                                            },
                                        },
                                    }),
                                ]
                            );
                        },
                    });
                    break;
                case '元数据':
                    _this.vmMetadata = true;

                    _this.metadataData = [
                        {
                            key: '',
                            value: '',
                        },
                    ];
                    _this.reachVmMetaData(params.id);
                    _this.vmName = params.name;
                    _this.vmId_ = params.id;
                    break;
                case '端口转发':
                    _this.vmName = params.name;
                    _this.vmId_ = params.id;
                    _this.portTableData = [];
                    _this.portListPanel = true;
                    _this.reachVmPortsList(params.id);
                    break;
                default:
                    console.log('不识别命令：' + text);
                    break;
            }
        },
        //查询虚拟机的状态
        reachVmStatus(vmId) {
            let _this = this;
            axios({
                url: 'topo-control/servers/' + vmId + '/status',
            }).then(function (response) {
                if (response.code == 1) {
                    if (response.list[0].taskStatus != 'null') {
                        _this.reachVmStatus(vmId);
                    } else {
                        _this.getVmListManage();
                        // var status = response.list[0].status;
                    }
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        //批量查询虚拟机状态
        reachManyVmStatus(vmIdGroup) {
            let _this = this;
            axios({
                url: 'topo-control/servers/batch_status',
                method: 'POST',
                data: vmIdGroup,
            }).then(function (response) {
                if (response.code == 1) {
                    let status_null = [];
                    let vm_status = '',
                        vm_loading = false;
                    _this.vmGroupStatus = response.list.map((item) => {
                        if (item.taskStatus != 'null') {
                            status_null.push(item.vmId);
                            vm_status = item.taskStatus;
                            vm_loading = true;
                        } else {
                            vm_status = item.status;
                            vm_loading = false;
                        }
                        return {
                            id: item.vmId,
                            status: vm_status,
                            loading: vm_loading,
                        };
                    });
                    if (status_null.length != 0) {
                        console.log(status_null);
                        _this.reachManyVmStatusSend(status_null);
                    }
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        reachManyVmStatusSend(vmIdGroup) {
            // console.log('----');
            let _this = this;
            clearTimeout(_this.setTimeClear);
            axios({
                url: 'topo-control/servers/batch_status',
                method: 'POST',
                data: vmIdGroup,
            }).then(function (response) {
                if (response.code == 1) {
                    let status_null = [];
                    let status_new = [];
                    let vm_status = '';
                    status_new = response.list.map((item) => {
                        if (item.taskStatus != 'null') {
                            status_null.push(item.vmId);
                            vm_status = item.taskStatus;
                            // return
                        } else {
                            vm_status = item.status;
                        }
                        return {
                            id: item.vmId,
                            status: vm_status,
                        };
                    });
                    _this.vmGroupStatus.forEach((item) => {
                        status_new.forEach((element) => {
                            if (item.id == element.id) {
                                item.status = element.status;
                            }
                        });
                    });
                    // console.log(_this.vmGroupStatus.length)
                    if (status_null.length != 0) {
                        // console.log(status_null)
                        _this.setTimeClear = setTimeout(() => {
                            // console.log('----------')
                            _this.reachManyVmStatusSend(status_null);
                        }, 3000);
                    }
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        updatePassword(vmId, btnLoading) {
            let _this = this;
            if (!_this.vmPassword) {
                _this.$Message.info('请输入密码');
                btnLoading = false;
                return;
            }
            axios({
                url: 'remote/changePassword/' + vmId + '?password=' + _this.vmPassword,
            }).then(function (response) {
                if (response.code == 1) {
                    _this.$Message.success('修改成功');
                    _this.getVmListManage();
                    _this.$Modal.remove();
                    _this.updatePasswordLoading = false;
                    _this.$nextTick(() => {
                        _this.updatePasswordLoading = true;
                    });
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                    btnLoading = false;
                    _this.$nextTick(() => {
                        btnLoading = true;
                    });
                }
            });
        },
        //批量修改生成随机密码
        updateVmPasswordMany(vmId) {
            let _this = this;
            return axios({
                url: 'remote/changePassword/' + vmId + '?password=' + _this.getRandomPassword(6),
            }).then(function (response) {
                if (response.code == 1) {
                    // _this.$Message.success("修改成功")
                    // _this.getVmListManage();
                    // _this.$Modal.remove()
                    // _this.updatePasswordLoading = false;
                    // _this.$nextTick(()=>{
                    //     _this.updatePasswordLoading = true;
                    // })
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                    // btnLoading = false;
                    // _this.$nextTick(()=>{
                    //     btnLoading= true;
                    // })
                }
            });
        },
        getRandomPassword(range) {
            let str = '',
                // range = 6,
                arr = [
                    'a',
                    'b',
                    'c',
                    'd',
                    'e',
                    'f',
                    'g',
                    'h',
                    'i',
                    'j',
                    'k',
                    'l',
                    'm',
                    'n',
                    'o',
                    'p',
                    'q',
                    'r',
                    's',
                    't',
                    'u',
                    'v',
                    'w',
                    'x',
                    'y',
                    'z',
                    'A',
                    'B',
                    'C',
                    'D',
                    'E',
                    'F',
                    'G',
                    'H',
                    'I',
                    'J',
                    'K',
                    'L',
                    'M',
                    'N',
                    'O',
                    'P',
                    'Q',
                    'R',
                    'S',
                    'T',
                    'U',
                    'V',
                    'W',
                    'X',
                    'Y',
                    'Z',
                    '0',
                    '1',
                    '2',
                    '3',
                    '4',
                    '5',
                    '6',
                    '7',
                    '8',
                    '9',
                ];
            // if (randomFlag) {
            //     range = Math.round(Math.random() * (max - min)) + min;// 任意长度
            // }
            for (let i = 0; i < range; i++) {
                let pos = Math.round(Math.random() * (arr.length - 1));
                str += arr[pos];
            }
            return str;
        },
        reachVmMetaData(vmId) {
            let _this = this;
            axios({
                url: 'topo-control/servers/' + vmId + '/metadata',
                method: 'get',
            }).then(function (response) {
                if (response.code == 1) {
                    _this.metadataData = [];
                    let metadata_ = response.attribute.metadata;
                    if (JSON.stringify(metadata_) == '{}') {
                        _this.metadataData.push({
                            key: '',
                            value: '',
                        });
                    } else {
                        for (let i in metadata_) {
                            _this.metadataData.push({
                                key: i,
                                value: metadata_[i],
                            });
                        }
                    }
                } else {
                    _this.$Message.error({
                        content: response.message,
                        duration: 10,
                        closable: true,
                    });
                }
            });
        },
        updateVmMetadata(vmId) {
            let _this = this;
            let objMedata = {};
            _this.metadataData.forEach((element) => {
                objMedata[element.key] = element.value;
            });
            axios({
                url: 'topo-control/servers/' + vmId + '/metadata',
                method: 'put',
                data: objMedata,
            }).then(function (response) {
                if (response.code == 1) {
                    _this.$Message.success('保存成功');
                    _this.vmMetadata = false;
                    _this.vmMetadataLoading = false;
                    _this.$nextTick(() => {
                        _this.vmMetadataLoading = true;
                    });
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                    _this.vmMetadataLoading = false;
                    _this.$nextTick(() => {
                        _this.vmMetadataLoading = true;
                    });
                }
            });
        },
        deleteVmMetadata(vmId, key) {
            let _this = this;
            axios({
                url: 'topo-control/servers/' + vmId + '/metadata/' + key,
                method: 'delete',
            }).then(function (response) {
                if (response.code == 1) {
                    // _this.
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        //查询虚拟机的key
        getVmAttributeKey(value) {
            if (!value) {
                return;
            }
            let _this = this;
            axios({
                url: 'topo-edit/topo/' + _this.prjId + '/attribute/tree?type=VM',
            }).then(function (response) {
                if (response.code == 1) {
                    // _this.vmKeys = []
                    if (response.attribute.result != '{}') {
                        // console.log(Object.keys(response.attribute.result))
                        _this.vmAttributeData = Object.keys(response.attribute.result).map(
                            (item) => {
                                let oneMenu = [
                                    {
                                        label: '--',
                                        value: '--',
                                    },
                                ];
                                // $.ajax({
                                //     type:"get",
                                //     contentType:"application/json",
                                //     async:false,
                                //     url: _projPath+'topo-edit/'+_this.prjId+"/attribute/key/"+item,
                                //     dataType:"json",
                                //     headers:{"Authorization":localStorage.token},
                                //     success: function (response) {
                                //  	    if(response.attribute.result.length!=0){
                                //             oneMenu = response.attribute.result.map(item=>{
                                //                 return{
                                //                     value:item,
                                //                     label:'value：'+item
                                //                 }
                                //             });
                                //         }
                                //     },
                                //     error: function () {
                                //     },
                                // });
                                return {
                                    value: item,
                                    label: 'key：' + item,
                                    children: oneMenu,
                                };
                            }
                        );
                        console.log(_this.vmKeys);
                    }
                } else {
                    if (response.code != -2) {
                        _this.$Message.error({
                            content: response.message,
                            closable: true,
                            duration: 10,
                        });
                    }
                }
            });
        },
        //通过key 查找value
        getValueByVmKey(vmAttributeKey) {
            console.log(vmAttributeKey);
            let _this = this;
            _this.vmValues = [];
            _this.virtualValueOfReach = '';
            if (!vmAttributeKey) {
                return;
            }
            axios({
                url: 'topo-edit/topo/' + _this.prjId + '/attribute/key/' + vmAttributeKey,
            }).then(function (response) {
                if (response.code == 1) {
                    if (response.attribute.result.length != 0) {
                        _this.vmValues = response.attribute.result;
                    }
                } else {
                    _this.$Message.error({
                        content: response.message,
                        closable: true,
                        duration: 10,
                    });
                }
            });
        },
        listenKeyChange(vmAttributeKey) {
            console.log(vmAttributeKey);
            let _this = this;
            // _this.vmValues = [];
            // _this.virtualValueOfReach = "";
            if (!vmAttributeKey) {
                _this.virtualKeyOfReach = '';
                _this.virtualValueOfReach = '';
                return;
            } else {
                if (vmAttributeKey.length == 1) {
                    _this.virtualKeyOfReach = vmAttributeKey[0];
                    _this.virtualValueOfReach = '';
                    axios({
                        url: 'topo-edit/topo/' + _this.prjId + '/attribute/key/' + vmAttributeKey[0],
                    }).then(function (response) {
                        if (response.code == 1) {
                            if (response.attribute.result.length != 0) {
                                // _this.vmValues = response.attribute.result;
                                for (let i = 0; i < _this.vmAttributeData.length; i++) {
                                    if (_this.vmAttributeData[i].value == vmAttributeKey[0]) {
                                        _this.vmAttributeData[i].children = [];
                                        response.attribute.result.forEach((element) => {
                                            _this.vmAttributeData[i].children.push({
                                                label: 'value：' + element,
                                                value: element,
                                            });
                                        });
                                        return;
                                    }
                                }
                            }
                        } else {
                            _this.$Message.error({
                                content: response.message,
                                closable: true,
                                duration: 10,
                            });
                        }
                    });
                } else {
                    _this.virtualKeyOfReach = vmAttributeKey[0];
                    _this.virtualValueOfReach = vmAttributeKey[1];
                }
            }
            _this.vmCurrentPage = 1;
            sessionStorage.setItem('vmCurrentPage', 1);
            _this.getVmListManage();
            // axios({
            //     url:'topo-edit/topo/'+_this.prjId+'/attribute/key/'+vmAttributeKey,
            // }).then(function(response){
            //     if(response.code==1){
            //         if(response.attribute.result.length!=0){
            //             // _this.vmAttributeData.forEach(element=>{
            //             //     if(){

            //             //     }
            //             // });
            //             for(let i=0;i<_this.vmAttributeData.length;i++){
            //                 if(_this.vmAttributeData[i].value==vmAttributeKey){
            //                     _this.vmAttributeData[i]['children'] = response.attribute.result.map(item=>{
            //                         return {
            //                             label:item,
            //                             value:item
            //                         }
            //                     });
            //                     return;
            //                 }
            //             }
            //         }
            //     }else{
            //         _this.$Message.error({content:response.message,closable:true,duration:10})
            //     }
            // })
        },
        opeartionManyVm() {
            let _this = this;
            if (this.selectTableDataGroup.length != 0) {
                // _this.isSpinShow = true
                _this.loadingTable = true;
                // let vmGroupStatus = this.selectTableDataGroup.map(item=>{
                //     return item.status;
                // });
                let vmGroupStatus = [];
                axios({
                    url: 'topo-control/servers/batch_status',
                    method: 'POST',
                    data: _this.selectTableDataGroup.map((item) => {
                        return item.id;
                    }),
                })
                    .then(function (response) {
                        if (response.code == 1) {
                            let vm_status = '';
                            return (vmGroupStatus = response.list.map((item) => {
                                if (item.taskStatus != 'null') {
                                    vm_status = item.taskStatus;
                                } else {
                                    vm_status = item.status;
                                }
                                return vm_status;
                            }));
                        } else {
                            _this.loadingTable = false;
                            _this.$Message.error({
                                content: response.message,
                                closable: true,
                                duration: 10,
                            });
                        }
                    })
                    .then(function (vmGroupStatus) {
                        _this.vmManyNumber = vmGroupStatus.length;
                        // vmGroupStatus = new Set(vmGroupStatus);
                        let uniqueArr = [...new Set(vmGroupStatus)];
                        _this.loadingTable = false;
                        if (uniqueArr.length != 1) {
                            _this.$Message.info('您选择的虚拟机中，存在不同状态的虚拟机');
                        } else {
                            _this.vmManyPanel = true;
                            // console.log(uniqueArr[0])
                            switch (uniqueArr[0]) {
                                case 'ACTIVE':
                                    _this.btnData = [
                                        '关机',
                                        '重启',
                                        '重置',
                                        '挂起',
                                        '暂停',
                                        '修改密码(系统随机生成)',
                                    ];
                                    break;
                                case 'Running':
                                    _this.btnData = [
                                        '关机',
                                        '重启',
                                        '重置',
                                        '挂起',
                                        '暂停',
                                        '修改密码(系统随机生成)',
                                    ];
                                    break;
                                case 'SHUTOFF':
                                    _this.btnData = ['开机', '重置'];
                                    break;
                                case 'DOWN':
                                    _this.btnData = ['开机', '重置'];
                                    break;
                                case 'Stopped':
                                    _this.btnData = ['开机', '重置'];
                                    break;
                                case 'SUSPENDED':
                                    _this.btnData = ['恢复'];
                                    break;
                                case 'ERROR':
                                    _this.btnData = ['重启', '重置状态'];
                                    break;
                                case 'PAUSED':
                                    _this.btnData = ['取消暂停'];
                                    break;
                                case 'CRUSH': //虚拟机奔溃状态
                                    _this.btnData = ['关机', '重启'];
                                    break;
                                case 'UNKNOWN': //虚拟机未知状态
                                    _this.btnData = [];
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
            } else {
                _this.$Message.info('请选择要操作的虚拟机');
            }
        },
        selectTableData(values) {
            this.selectTableDataGroup = values;
            // console.log(values)
        },
        testFgm(value) {
            this.selectTableDataGroup.forEach((element) => {
                this.vmSwitchTypeOperation(element.id, value, '', true);
            });
        },
        okVm(value) {
            let _this = this;
            let activeFunction = [];
            activeFunction = this.selectTableDataGroup.map((element) => {
                let vmId = element.id;
                let batch = true;
                return new Promise((resolve, reject) => {
                    switch (value) {
                        case '关机':
                            _this.operationVm(vmId, 'stop', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '开机':
                            _this.operationVm(vmId, 'start', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '重启':
                            _this.rebootVm(vmId, batch).then(() => {
                                resolve();
                            });
                            break;
                        case '重置':
                            _this.rebuildVm(vmId, batch).then(() => {
                                resolve();
                            });
                            break;
                        case '挂起':
                            _this.operationVm(vmId, 'suspend', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '暂停':
                            _this.operationVm(vmId, 'pause', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '恢复':
                            _this.operationVm(vmId, 'resume', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '取消暂停':
                            _this.operationVm(vmId, 'unpause', batch).then(() => {
                                resolve();
                            });
                            break;
                        case '修改密码(系统随机生成)':
                            _this.updateVmPasswordMany(vmId).then(() => {
                                resolve();
                            });
                            // _this.operationVm(vmId,'unpause',batch).then(()=>{
                            //     resolve()
                            // })
                            break;
                        default:
                            break;
                    }
                });
                // return this.vmSwitchTypeOperation(element.id,value,'',true)
            });
            console.log(activeFunction);
            // setTimeout(() => {
            //     this.reachManyVmStatusSend(this.vmIdGroupStatus);
            // }, 1500);
            this.vmManyPanel = false;
            Promise.all(activeFunction).then(() => {
                // console.log('----------');
                _this.getVmListManage();
                // _this.reachManyVmStatusSend(_this.vmIdGroupStatus);
            });
            return;
            // let promise = new Promise(()=>{

            // }).then((value)=>{
            //     console.log(value);

            // })
            // let _this = this;
            // let group = [];
            // group = this.selectTableDataGroup.map(element=>{
            //     return _this.vmSwitchTypeOperation(element.id,value,'',true)
            // });
            // let promise = new Promise((resolve, reject) => {
            //     // let i = 0;
            //     this.selectTableDataGroup.forEach((element,index)=>{
            //         // group.push(this.vmSwitchTypeOperation(element.id,value,'',true));
            //         this.vmSwitchTypeOperation(element.id,value,'',true)
            //         // i++;
            //     });

            //     resolve();
            //     // if(i==this.selectTableDataGroup.length){
            //     //     resolve();
            //     // }
            // });
            // promise.then((value) => {
            //     console.log(value)
            //     this.reachManyVmStatusSend(this.vmIdGroupStatus);
            // }).then(()=>{
            //     this.vmManyPanel = false;
            // });
            // console.log(promise)
            // promise.then((value) => {
            //     console.log(value)
            //     this.reachManyVmStatusSend(this.vmIdGroupStatus);
            // }).then(()=>{
            //     this.vmManyPanel = false;
            // });
            // this.reachManyVmStatusSend(this.selectTableDataGroup.map(item=>{return item.id}));
            // console.log(this.vmIdGroupStatus)
            //    setTimeout(() => {

            //    }, 2000);
        },
        test(value) {
            // console.log(value)
        },
        reachVmPortsList(vmId) {
            let _this = this;
            _this.portTableData = [];
            return axios({
                url: 'netns/access/detail?vmId=' + vmId,
                method: 'get',
                // params:{
                //     vmId:vmId
                // }
            }).then((response) => {
                if (response.code == 1) {
                    // return response.attribute.result
                    response.attribute.result.pageData.forEach( function (item,i) {
                        if (item.forwardIp) {
                            _this.portTableData.push(item);
                        }
                    });
                    // _this.portTableData = response.attribute.result.pageData.filter((item)=>{
                    //     return item.forwardIP;
                    // });
                } else if (response.code == -2) {
                    _this.portTableData = [];
                } else {
                    _this.$Message.error(response.message);
                }
            });
        },
        deleteVmPort(token) {
            let _this = this;
            axios({
                url: '/netns/access/disConnet/' + token,
                method: 'delete',
            }).then((response) => {
                if (response.code == 1) {
                    _this.reachVmPortsList(this.vmId_);
                } else {
                    _this.$Message.error(response.message);
                }
            });
        },
        listenTypeChange(value) {
            console.log(value);
            let _this = this;
            _this.disabledprototol = true;
            _this.disabledType = true;
            switch (value) {
                case 'ssh':
                    _this.formValidate.port = 22;
                    _this.formValidate.protocol = 'tcp';
                    _this.disabledType = false;
                    _this.formValidate.customType = 'test';
                    break;
                case 'rdp':
                    _this.formValidate.port = 3389;
                    _this.formValidate.protocol = 'tcp';
                    _this.disabledType = false;
                    _this.formValidate.customType = 'test';
                    break;
                case 'vnc_in':
                    _this.formValidate.port = 5901;
                    _this.formValidate.protocol = 'tcp';
                    _this.disabledType = false;
                    _this.formValidate.customType = 'test';
                    break;
                case 'other':
                    // _this.formValidate.port = 22
                    _this.disabledprototol = false;
                    _this.disabledType = true;
                    _this.formValidate.port = 1;
                    _this.formValidate.customType = '';
                    break;
                default:
                    break;
            }
        },
        deleteAccessAisle(vmId) {
            let _this = this;
            axios({
                url: 'netns/access/vms/' + vmId,
                method: 'delete',
            }).then((response) => {
                if (response.code == 1) {
                    _this.$Message.success('刷新成功');
                    _this.loadingTable = false;
                } else {
                    _this.$Message.success(response.message);
                    _this.loadingTable = false;
                }
            });
        },
        limitingReach() {
            let _this = this;
            clearTimeout(_this.setTimeoutReach);
            _this.setTimeoutReach = setTimeout(() => {
                _this.getVmListManage();
            }, 500);
        },
        reachNetworkList(value) {
            if (!value) {
                return;
            }
            let _this = this;
            axios({
                url: 'topo-edit/topo/project/' + _this.prjId + '/tree',
                method: 'GET',
                data: 'NW',
            }).then(function (response) {
                if (response.code == 1) {
                    _this.networkData = [];
                    let networkDataTree = response.data;
                    function getNetwork(currentNetworkData) {
                        // if(currentNetworkData.name!="rootNetwork"){
                        _this.networkData.push({
                            networkName: currentNetworkData.name,
                            networkId: currentNetworkData.id,
                        });
                        // }
                        if (
                            currentNetworkData.networks &&
                            currentNetworkData.networks.length != 0
                        ) {
                            for (let i = 0; i < currentNetworkData.networks.length; i++) {
                                getNetwork(currentNetworkData.networks[i]);
                            }
                        }
                    }
                    getNetwork(networkDataTree);
                    console.log(_this.networkData);
                } else {
                    _this.$Message.error(response.message);
                }
            });
        },
        reachSubnetList(value) {
            if (!value) {
                return;
            }
            let _this = this;
            axios({
                url: 'deploy/project/subnets?prjId=' + _this.prjId + '&page=1&rows=20000',
                method: 'GET',
            }).then(function (response) {
                if (response.code == 1) {
                    _this.subnetData = response.data.list;
                } else {
                    _this.$Message.error(response.message);
                }
            });
        },
        reachSegmentList(value) {
            console.log(value);
            if (!value) {
                return;
            }
            let _this = this;
            axios({
                url: 'deploy/project/segments?prjId=' + _this.prjId + '&page=1&rows=20000',
                method: 'GET',
            }).then(function (response) {
                if (response.code == 1) {
                    _this.segmentsData = response.data.list;
                } else {
                    _this.$Message.error(response.message);
                }
            });
        },
    },
};
</script>

<style scoped>
.headerBtn1 {
    text-align: left;
    margin: 0 0 15px;
}
.pageStyle1 {
    text-align: center;
    margin-top: 15px;
}

.operation .ivu-select-arrow {
    right: 2px;
}
.operation .ivu-select-selection {
    border-radius: 0px 4px 4px 0px;
}
.accessType .ivu-select-arrow {
    right: 2px;
}
.accessType .ivu-select-selection {
    border-radius: 0px 4px 4px 0px;
}
.opertionVm .ivu-select-arrow {
    right: 2px;
}
.opertionVm .ivu-select-selection {
    border-radius: 0px 4px 4px 0px;
}
.ivu-table-wrapper {
    /* overflow: visible !important; */
}
.ivu-tag-border.ivu-tag-closable .ivu-icon-ios-close {
    top: -2px;
}
.ivu-table-tip {
    /* overflow: hidden !important; */
}

.expendSpanStyle {
    display: inline-block;
    margin-right: 25px;
    min-width: 300px;
}
</style>
